<template>
  <div style="border: 1px solid #ccc" :style="{ width: '100%' }">
    <div ref="toolbarRef" v-show="showToolbar" style="border-bottom: 1px solid #ccc"></div>
    <div ref="editorRef" :style="{ height: editorHeight, overflowY: 'hidden' }"></div>
  </div>
</template>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import { IDomEditor, IEditorConfig, IToolbarConfig, createEditor, createToolbar } from '@wangeditor/editor'
import axios from 'axios'
import storage from '../utils/storage'

// Props
const props = withDefaults(
  defineProps<{
    modelValue?: string
    editorHeight?: string
    readOnly?: boolean
    showToolbar?: boolean
  }>(),
  {
    editorHeight: '500px',
    readOnly: false,
    showToolbar: true,
  }
)

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

// 模板引用
const toolbarRef = ref<HTMLDivElement>()
const editorRef = ref<HTMLDivElement>()

// 编辑器实例
const editorObj = shallowRef<IDomEditor | null>(null)

// 工具栏配置 - 排除不需要的按钮
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: [
    'emotion', // 表情
    'divider', // 分隔线
    'group-indent', // 缩进
    'group-video', // 视频
    'insertTable', // 表格
    'insertLink', // 超链接
    'codeBlock', // 代码块
  ],
}

// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  placeholder: props.readOnly ? '暂无内容' : '请输入内容...',
  readOnly: props.readOnly,
  MENU_CONF: {
    uploadImage: {
      server: '/dev-api/oa/woorder/avatar',
      fieldName: 'avatarfile',
      maxFileSize: 5 * 1024 * 1024,
      allowedFileTypes: ['image/*'],
      headers: {
        Authorization: `Bearer ${storage.get('CURRENT_TOKEN', '')}`,
      },
      async customUpload(file: File, insertFn: any) {
        const formData = new FormData()
        formData.append('avatarfile', file)

        try {
          const token = storage.get('CURRENT_TOKEN', '')
          const response = await axios.post('/dev-api/oa/woorder/avatar', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              Authorization: `Bearer ${token}`,
            },
          })

          console.log('response:', response)

          if (response.data.code === 200 && response.data.imgUrl) {
            insertFn(response.data.imgUrl, '', '')
          } else {
            console.error('图片上传失败:', response.data.msg)
          }
        } catch (err) {
          console.error('图片上传错误:', err)
        }
      },
      onBeforeUpload(file: File) {
        if (file.size > 5 * 1024 * 1024) {
          console.error('图片大小不能超过5M')
          return false
        }
        return true
      },
      onProgress(progress: number) {
        console.log('上传进度:', progress)
      },
      onSuccess(_: File, res: any) {
        console.log('上传成功:', res)
      },
      onError(_: File, err: any, res: any) {
        console.error('上传失败:', err, res)
      },
    },
  },
}

// 初始化编辑器
onMounted(() => {
  if (!toolbarRef.value || !editorRef.value) return

  const editor = createEditor({
    selector: editorRef.value,
    config: editorConfig,
    html: props.modelValue || '',
  })

  // 只有在需要显示工具栏时才创建工具栏
  if (props.showToolbar) {
    createToolbar({
      editor,
      selector: toolbarRef.value,
      config: toolbarConfig, // 正确传递 toolbarConfig
    })
  }

  editorObj.value = editor

  editor.on('change', () => {
    const content = editor.getHtml()
    emit('update:modelValue', content)
  })
})

// 监听 readOnly 属性变化
watch(
  () => props.readOnly,
  (newVal) => {
    if (editorObj.value) {
      editorObj.value.enable()
      if (newVal) {
        editorObj.value.disable()
      }
    }
  }
)

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (editorObj.value) {
      const curContent = editorObj.value.getHtml()
      if (newVal !== curContent) {
        try {
          editorObj.value.setHtml(newVal || '')
        } catch (err) {
          // console.warn('Invalid content format', err)
        }
      }
    }
  },
  { deep: true }
)

// 销毁编辑器
onBeforeUnmount(() => {
  const editor = editorObj.value
  if (editor == null) return
  editor.destroy()
})

defineExpose({
  getEditor: () => editorObj.value,
  setHtml: (html: string) => {
    if (editorObj.value) {
      editorObj.value.setHtml(html || '')
    }
  },
  getHtml: () => {
    return editorObj.value ? editorObj.value.getHtml() : ''
  },
})

export type EditorType = typeof editorObj.value
</script>
